# -*- coding:utf-8 -*-
"""
Created on 4 aug 2012

@author: Olof Manbo
"""

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db

import simplejson

import os
import logging
import models

class Todos(webapp.RequestHandler):
    def get(self):
        html = simplejson.dumps([
                                 {"text": "Polera Hummrar", "done": False}
                                 ])
        self.response.out.write(html)

class TopBarData(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            admin_key = db.Key.from_path('Administrator', user.user_id())
            admin = db.get(admin_key)
            logging.info(admin)
            if admin is not None:
                players = []
                for name, key_name in zip(admin.players, admin.playerIds):
                    players.append({"name": name, "id": key_name})
                html = simplejson.dumps(
                                        {"logOutUrl": users.create_logout_url("/"),
                                        "players": players,
                                         }
                                        )
                self.response.out.write(html)

class FilteredPlayerList(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            # Prepare a query.
            q = models.Player.all()
            logging.info(self.request.arguments())
            beginning = self.request.get("beginning")
            logging.info(beginning)
            # The query is not executed until results are accessed.
            results = q.run()
            #for p in results:
            #    logging.info(p.userName)
            reply = [{"name": r.userName, "id": r.key().name()} for r in results if r.userName.lower().find(beginning ,0, len(beginning)) != -1]
            logging.info(reply)
            html = simplejson.dumps(reply)
            self.response.out.write(html)
            
class Player(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            # Prepare a query.
            
            key_name = self.request.get("id")
            player_key = db.Key.from_path('Player', key_name)
            player = db.get(player_key)
            reply = {"name": player.userName,
                     "date": str(player.date),
                     "id": player.key().name()}
            html = simplejson.dumps(reply)
            self.response.out.write(html)
            
            
            
            
            